﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR_WPF.TranslateHelper
{
    class BaiduTranslate : ITranslate
    {
        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId;
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret;
        public BaiduTranslate()
        {
            clientId = ConfigurationManager.AppSettings["Baidu_Translate_Id"];
            clientSecret = ConfigurationManager.AppSettings["Baidu_Translate_Key"];
        }
        public string SendContent(string content)
        {
            String authHost = "https://fanyi-api.baidu.com/api/trans/vip/translate";
            RestClient restClient = new RestClient(authHost);
            RestRequest restRequest = new RestRequest(Method.POST);

            restRequest.AddParameter("q", content);
            restRequest.AddParameter("from", "auto");//原语言
            restRequest.AddParameter("to", "zh");//目标语言
            restRequest.AddParameter("appid", clientId);
            restRequest.AddParameter("salt", "011225");
            restRequest.AddParameter("sign", getSign(content));

            var result = restClient.Execute(restRequest);

            try
            {
                var lst = new List<string>();
                dynamic json = JsonConvert.DeserializeObject(result.Content);
                foreach (var item in json.trans_result)
                {
                    lst.Add(item.dst.ToString());
                }
                return string.Join("\r\n\r\n    ", lst);
            }
            catch (Exception)
            {
                return "翻译失败";
            }
        }   

        protected string getSign(string q)
        {
            string sign = string.Format("{0}{1}{2}{3}", clientId, q, "011225", clientSecret);
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }
    }
}
